using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class ScoreManager : MonoBehaviour
{
    public PointTrigger pointTrigger;
    public Transform HurtNumberPos;
    public GameObject HurtNumberPrefab;
    
    private int score = 100;

    public Text TextMesh;
    public AudioClip[] hoories;

    private float timeLeft;
    private int curScore = 1;

    private bool ShouldAddScore = false;

    private float gameTime = 0;

    private AudioSource audioSource;

    public void Start()
    {
        audioSource = GetComponent<AudioSource>();
        score = 0;
        TextMesh.text = score + " ";
        Basket.ScoreTextPos = HurtNumberPos.position;
    }

    public void Update()
    {
        gameTime += Time.deltaTime;
    }

    public void AddScore()
    {
        ShouldAddScore = true;
    }

    public void UpdateScorePanel()
    {
        TextMesh.text = score + " ";
    }

    public int GetScore()
    {
        return score;
    }

    public int GetCurScore() 
    {
        return curScore;
    }


    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            timeLeft = gameTime;
        }
    }

    void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            timeLeft = gameTime - timeLeft;
            if (ShouldAddScore)
            {
                if (timeLeft < 0.3f)
                {
                    curScore++;
                    score += curScore;
                    if (curScore > 2)
                    {
                        audioSource.PlayOneShot(hoories[Random.Range(0, hoories.Length)]);
                    }
                    UpdateScorePanel();
                }
                else
                {
                    curScore = 1;
                    score += curScore;
                    UpdateScorePanel();
                }
                PopUpHurtNumber(curScore);
                ShouldAddScore = false;

            }
        }    
    } 

    public void PopUpHurtNumber(int damage)
    {
        GameObject hurtNumber = Instantiate(HurtNumberPrefab, Basket.ScoreTextPos, Quaternion.identity);
        hurtNumber.transform.DOMoveY(Basket.ScoreTextPos.y + 1, 1f);
        TextMeshPro textMeshProUGUI = hurtNumber.transform.GetChild(0)
             .GetComponentInChildren<TextMeshPro>();

        textMeshProUGUI.text = "+" + damage.ToString();
        Destroy(hurtNumber, 1f);
        Basket.ScoreTextPos = HurtNumberPos.position;
    }
    
}